import type { SetDeckQueryParams, SetDeckList, SetDeckItem } from '/@/api/deckSet/model/setDeckModel';
import { SearchSettingTypeEnum } from '/@/api/currentDeck/model/deckModel';
import { defineComponent, reactive, ref, toRaw, unref, onActivated } from 'vue';
import { useDeckSetStore } from '/@/store/modules/deckSet';
import { useUserStore } from '/@/store/modules/user';
import { useSetDeckConfigHooks } from '/@/views/deskSet/hooks/useSetConfigs';
import { useGo } from '/@/hooks/web/usePage';
import { useGlobSetting } from '/@/hooks/setting';
import { cloneDeep, find } from 'lodash-es';
import { formatToDateTime } from '/@/utils/dateUtil';
import { appShareUsing, getAppParameters } from '/@/utils/appInteractive';
import { aTabClick, awaitWrap, filterNullAttributes } from '/@/utils';
import Title from '/@/views/general/components/Title';
import { Button, Empty, Field, List, Tag, BackTop } from 'vant';
import { Icon } from '/@/components/Icon';
import ListFilterBox from './components/ListFilterBox';
import { SetDeckListApi } from '/@/api/deckSet/setDeck';

import('./index.less');
export default defineComponent({
  name: 'DeskSetListPage',
  props: {
    gameId: {
      type: String as PropType<string>,
      required: true,
    },
  },
  // @ts-ignore
  setup(props) {
    // 设置分享参数
    getAppParameters(); // 需要重新获取一下token 因为是在app使用
    appShareUsing({} as any);

    const go = useGo();
    const globSetting = useGlobSetting();
    const userStore = useUserStore();

    // 获取配置
    const { getDeckConfig, searchConfigData, showConfigData } = useSetDeckConfigHooks();
    getDeckConfig({ game_id: props.gameId });

    const setStore = useDeckSetStore();
    setStore.setGameId(props.gameId);

    const queryState = reactive<SetDeckQueryParams>({
      game_id: props.gameId,
      page: 1,
      page_size: 10,
      deck_name: '',
      tags: [],
      card_ids: [],
    });
    // region 动态搜索条件
    const selectedFilterKey = ref<string>('');
    const selectedFilterKeyClick = <T extends string>(text: T) => {
      if (unref(selectedFilterKey) === text) {
        selectedFilterKey.value = '';
        return;
      }
      selectedFilterKey.value = text;
    };
    const FilterItemNode = () => {
      return (
        <>
          {searchConfigData.map((item) => {
            return (
              <li
                class={[
                  'flex items-center text-sm flex-shrink-0 mr-xl',
                  { 'text-blue-500': queryState[item.attr_key]?.length },
                ]}
                onClick={() => {
                  selectedFilterKeyClick(item.attr_key);
                }}
              >
                <span>{item.title}</span>
                <Icon icon={'mdi:triangle-small-down'} />
              </li>
            );
          })}
        </>
      );
    };

    // endregion
    // 数据获取
    const listLoading = ref(false); // 是否处于加载状态 默认不处于，流会去加载数据
    const listFinished = ref(false); // 是否全部数据加载完成
    const listEmpty = ref(false);
    const listData = reactive<SetDeckList>({
      total: 0,
      rows: [],
    });
    const getList = async (isRefresh: boolean) => {
      setStore.setIsAgainSearch(false);
      if (isRefresh) {
        queryState.page = 1;
        listData.rows = [];
        listData.total = 0;
        listLoading.value = true;
      }
      const params: SetDeckQueryParams = filterNullAttributes(cloneDeep(toRaw(queryState)), []);
      const [error, result] = await awaitWrap(SetDeckListApi(toRaw(params)));
      if (error || !result) {
        return;
      }
      if (queryState.page === 1) {
        listFinished.value = false;
        !result.rows.length ? (listEmpty.value = true) : (listEmpty.value = false);
      }
      for (const item of result.rows) {
        listData.rows.push(item);
      }
      listLoading.value = false;
      if (!result.rows.length) {
        listFinished.value = true;
        return;
      }
      queryState.page += 1;
    };

    //套牌列表
    const DeckItem = ({ deckItem }: { deckItem: SetDeckItem }) => {
      const { tags, show_attr, user_info, publish_at, deck_name, price } = deckItem;
      const TagNode: VueNode[] = [];
      if (tags.length) {
        tags.map((tag) => {
          TagNode.push(
            <Tag color={'linear-gradient(142deg, #4396ff 0%, #086acc 100%)'} size={'medium'} class='mr-sm mb-sm'>
              {tag}
            </Tag>
          );
        });
      }
      const AttrNode: VueNode[] = [];
      if (show_attr && show_attr.length) {
        show_attr.map((attr) => {
          const attrResult = find(showConfigData, ['attr_key', attr.attr_key]);
          if (!attrResult || !attr.value) {
            return;
          }
          const { mapping: attrMapping, show_type } = attrResult;
          const attrArr = attr.value.split(',');
          attrArr.map((val) => {
            if (!attrResult.is_mapping) {
              AttrNode.push(<span class={'mr-sm mb-sm'}>{val}</span>);
              return;
            }
            const attrVal = find(attrMapping, ['value', val]);
            if (!attrVal) {
              return;
            }
            show_type === SearchSettingTypeEnum.TEXT
              ? AttrNode.push(<span class={'mr-sm mb-sm'}>{attrVal.text}</span>)
              : AttrNode.push(<img class={'h-40px mr-sm mb-sm'} src={attrVal.text} alt='' />);
          });
        });
      }
      return (
        <li
          class={'deck-item flex text-sm'}
          onClick={() => {
            go(`/setdeckdetail/${deckItem.deck_id}`);
          }}
        >
          <div class={'flex-1'}>
            <div class={'van-ellipsis w-[420px]'}>{deck_name}</div>
            <div class={'flex items-center flex-wrap mt-sm'}>
              {TagNode}
              {AttrNode}
            </div>
            <div class={'text-xs'}>{price ? `预估: ${price / 100}元` : ''}</div>
          </div>
          <div class={'user-info text-gray-400 text-22px'}>
            <div class={'avatar flex items-center mb-md'}>
              <img class={'w-60px h-60px block mx-auto rounded-full'} src={user_info.avatar} />
              <img class='border-img' src={user_info.border} alt='' />
            </div>
            <div class={'w-full van-ellipsis text-center mb-sm'}>{user_info.nickname}</div>
            <div class={'w-full van-ellipsis text-center'}>{formatToDateTime(publish_at, 'YYYY-MM-DD')}</div>
          </div>
        </li>
      );
    };

    onActivated(() => {
      document.querySelector('.set-deck-back-top')?.setAttribute('style', 'visibility: visible');
      if (!setStore.getIsAgainSearch) {
        return;
      }
      queryState.card_ids = [];
      setStore.getSelectedCards.map((card) => {
        card ? queryState.card_ids?.push(String(card.id)) : null;
      });
      getList(true);
    });

    return () => (
      <div class='deck-set-list-page'>
        <Title title={'套牌广场'} />
        <div class='search-area'>
          <div class={'input-box'}>
            <Field v-model={[queryState.deck_name]} placeholder='卡牌名称或规则' leftIcon={'search'} clearable />
            <Button
              type={'primary'}
              color={'#000'}
              size={'small'}
              onClick={() => {
                getList(true);
              }}
            >
              搜索
            </Button>
          </div>
          <div class={'filter-area flex items-center justify-between'}>
            <ul class={'flex'}>
              <FilterItemNode />
            </ul>
            <div
              class={'flex items-center text-sm'}
              onClick={() => {
                go('/setdeckadcard');
              }}
            >
              <Icon icon='mdi:filter-multiple-outline' class={'-mt-2px'} />
              <span>高级搜索</span>
            </div>
          </div>
          <ListFilterBox
            attrKey={selectedFilterKey.value}
            queryState={queryState}
            searchConfigData={searchConfigData}
            onPageRefresh={() => {
              getList(true);
            }}
          />
        </div>
        <div class={'deck-list-container'}>
          {unref(listEmpty) ? (
            <Empty>暂无相关套牌</Empty>
          ) : (
            <List
              v-model={[listLoading.value, 'loading']}
              finished={unref(listFinished)}
              finishedText={'没有更多套牌'}
              onLoad={getList}
              offset={0}
            >
              <ul class='deck-list'>
                {listData.rows.map((deck) => {
                  return <DeckItem deckItem={deck} />;
                })}
              </ul>
            </List>
          )}
        </div>
        <div
          class={'bottom-action-box text-blue-500'}
          onClick={() => {
            if (!userStore.getToken) {
              aTabClick('wanxiu://innerlink?type=weblogin');
              return false;
            }
            const url = `wanxiu://innerlink?type=miniactivity&url=${globSetting.gadgetsUrl}/templatedeck/index.html#/currentdeck/${props.gameId}`;
            aTabClick(url);
          }}
        >
          我的套牌
        </div>
        <BackTop class={'set-deck-back-top'} />
      </div>
    );
  },
});
